import 'package:esc_pos_utils_plus/esc_pos_utils_plus.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'dart:async';
import 'package:image/image.dart' as image;
import 'package:flutter/services.dart';
import 'package:flutter_xprinter/connect_type.dart';
import 'package:flutter_xprinter/flutter_xprinter.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown';
  final _flutterXprinterPlugin = FlutterXprinter();

  @override
  void initState() {
    debugRepaintRainbowEnabled = true;
    super.initState();
    initPlatformState();
    _flutterXprinterPlugin.addMethodCallHandler((method, args) {
      print("$method : $args");
    });
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    String platformVersion;
    // Platform messages may fail, so we use a try/catch PlatformException.
    // We also handle the message potentially returning null.
    try {
      platformVersion = await _flutterXprinterPlugin.getPlatformVersion() ??
          'Unknown platform version';
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      _platformVersion = platformVersion;
    });
  }

  void _version() async {
    String? version = await _flutterXprinterPlugin.getPlatformVersion();
    print(version);
  }

  void _print(ConnectType connectType, DeviceType deviceType, String address) async {
    final profile = await CapabilityProfile.load(name: "XP-N160I");
    final generator = Generator(PaperSize.mm58, profile);
    List<int> bytes = [];
    bytes += generator.setGlobalCodeTable('CP1252');
    bytes += generator.text('世纪大道',
        styles: const PosStyles(align: PosAlign.center), containsChinese: true);
    bytes += generator.text('google.com');
    bytes += generator.qrcode('www.baidu.com');
    final List<int> barData = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 4];
    bytes += generator.barcode(Barcode.upcA(barData));
    bytes += generator.row([
      PosColumn(
        text: 'col3',
        width: 4,
        styles: const PosStyles(align: PosAlign.left, underline: true),
      ),
      PosColumn(
        text: 'col6',
        width: 4,
        styles: const PosStyles(align: PosAlign.center, underline: true),
      ),
      PosColumn(
        text: 'col3',
        width: 4,
        styles: const PosStyles(align: PosAlign.right, underline: true),
      ),
    ]);

    bytes += generator.feed(2);
    bytes += generator.emptyLines(3);
    bytes += generator.cut();
    _flutterXprinterPlugin.sendPrintTask(bytes, connectType, deviceType, address);
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
          child: Column(
            children: [
              ElevatedButton(
                  onPressed: () {
                    _flutterXprinterPlugin.connect(ConnectType.TYPE_BLE,
                        DeviceType.DEVICE_XPRINTER, "DC:0D:30:24:5B:FA");
                  },
                  child: const Text("BT")),
              ElevatedButton(
                  onPressed: () {
                    _flutterXprinterPlugin.connect(ConnectType.TYPE_USB,
                        DeviceType.DEVICE_GPRINTER, "/dev/bus/usb/001/004");
                  },
                  child: const Text("USB")),
              ElevatedButton(
                  onPressed: () {
                    _flutterXprinterPlugin.connect(ConnectType.TYPE_NET,
                        DeviceType.DEVICE_XPRINTER, "DC:0D:30:24:5B:FA");
                  },
                  child: const Text("NET")),
              ElevatedButton(
                  onPressed: () {
                    _flutterXprinterPlugin.disconnect("DC:0D:30:24:5B:FA");
                  },
                  child: const Text("DISCONNECT")),
              ElevatedButton(
                  onPressed: () {
                    _version();
                  },
                  child: const Text("VERSION")),
              ElevatedButton(
                  onPressed: () async {
                    _print(ConnectType.TYPE_USB, DeviceType.DEVICE_GPRINTER, "/dev/bus/usb/001/008");
                  },
                  child: const Text("佳博打印")),
              //DC:0D:30:24:5B:FA
              ElevatedButton(
                  onPressed: () async {
                    _print(ConnectType.TYPE_BLE, DeviceType.DEVICE_XPRINTER, "DC:0D:30:24:5B:FA");
                  },
                  child: const Text("芯烨打印")),
              ElevatedButton(
                onPressed: () async {
                  _flutterXprinterPlugin.scanBluetoothDevices();
                },
                child: const Text("扫描蓝牙设备"),
              ),
              ElevatedButton(
                onPressed: () async {
                  _flutterXprinterPlugin.scanUsbDevices();
                },
                child: const Text("USB设备"),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
